<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>购物车🔗数据库</title>
    <link rel="stylesheet" href="./css/style.css" />
    <link rel="stylesheet" href="https://at.alicdn.com/t/font_3246975_r7ow77w0bdn.css">
    <script src="../rest.js"></script>
    <style>
        .w {
            width: 1226px;
            margin: 0 auto;
        }

        .header {
            background-color: #f5f5f5;
        }

        .header .header-nav {
            height: 40px;
            line-height: 40px;
            overflow: hidden;
        }

        .header .header-nav .header-nav-l,
        .header .header-nav .header-nav-r {
            font-size: 12px;
            display: flex;
        }

        .header .header-nav li {
            padding-right: 20px;
        }

        .header .header-nav .header-nav-l {
            float: left;
        }

        .header .header-nav .header-nav-r {
            float: right;
        }

        .header .header-nav .header-nav-l .hide {
            display: none;
        }

        .sign-tips a:first-child,
        .sign-user a:first-child {
            margin-right: 5px;
        }

        .header-nav-search {
            margin-top: 4px;
            float: left;
        }

        .header-nav-search .searchBar {
            width: 240px;
            height: 30px;
            border: 1px solid #dfdfdf;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #fff;
            margin-left: 200px;
        }

        .header-nav-search .searchBar .searchCon {
            border: none;
            width: 210px;
            text-indent: 5px;
            background-color: transparent;
        }

        .header-nav-search .searchBar .searchBtn {
            width: 30px;
            height: 30px;
            font-size: 20px;
            text-align: center;
            line-height: 30px;
            color: #dfdfdf;
        }

        .catbox .empty {
            /* width: 100%; */
            /* min-height: 400px; */
            text-align: center;
            background-color: #f5f5f5;
        }

        .catbox .empty .title {
            line-height: 30px;
        }
    </style>
</head>

<body>
    <!-- 头部内容 登录/搜索 -->
    <div class="header">
        <div class="header-nav w">
            <ul class="header-nav-l">
                <li>湖北</li>
                <li class="sign-tips">
                    <a href="./login.html">亲,请登录</a>
                    <a href="./register.html">免费注册</a>
                </li>
                <li class="sign-user hide">
                    <a href="javascript:;" class="lg-user">欢迎您,xxx</a>
                    <a href="javascript:;" class="exit">退出登录</a>
                </li>
            </ul>
            <ul class="header-nav-search">
                <div class="searchBar">
                    <input type="text" class="searchCon">
                    <i class="iconfont icon-sousuo searchBtn"></i>
                </div>
            </ul>
            <ul class="header-nav-r">
                <li><a href="./index.html">我的淘宝</a></li>
                <li><a href="./shoppingCar.html">购物车</a></li>
                <li><a href="">收藏夹</a></li>
            </ul>
        </div>
    </div>
    <div class="catbox">
        <table id="cartTable">
            <thead>
                <tr>
                    <th><label>
                            <!-- 全选按钮 -->
                            <input class="check-all check" type="checkbox" />&nbsp;&nbsp;全选
                        </label></th>
                    <th>商品</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>小计</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <!-- <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/1.jpg" alt="" /><span>Casio/卡西欧 EX-TR350</span></td>
                    <td class="price">5999.88</td>
                    <td class="count">
                        <span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">5999.88</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>-->
            </tbody>
        </table>
        <div class="foot" id="foot">
            <a class="fl" id="deleteAll" href="javascript:;">删除</a>
            <div class="fr closing" onclick="">结 算</div>
            <input type="hidden" id="cartTotalPrice" />
            <div class="fr total">合计：￥<span id="priceTotal">0.00</span></div>
            <div class="fr selected" id="selected">已选商品<span id="selectedTotal">0</span>件<span
                    class="arrow up">︽</span><span class="arrow down">︾</span></div>
            <div class="selected-view">
                <div id="selectedViewList" class="clearfix">
                    <div><span>取消选择</span></div>
                </div>
                <span class="arrow">◆<span>◆</span></span>
            </div>
        </div>
    </div>
</body>
<script>
    var catbox = document.getElementsByClassName("catbox")[0]
    var checkAll = document.getElementsByClassName("check-all")[0]
    var checkOneList = document.getElementsByClassName("check-one")
    var selectedTotal = document.getElementById("selectedTotal")
    var priceTotal = document.getElementById("priceTotal")
    var tbody = document.getElementsByTagName('tbody')[0]
    //头部的元素获取
    var signTips = document.getElementsByClassName("sign-tips")[0]
    var signUser = document.getElementsByClassName("sign-user")[0]
    var outUserName = signUser.getElementsByClassName('exit')[0]
    var searchBtn = document.getElementsByClassName('searchBtn')[0]
    //点击搜索跳转到搜索界面
    searchBtn.onclick = function () {
        var wd = this.previousElementSibling.value
        location.href = "./searchGoods.html?wd=" + wd
    }
    //获取cookie用户名，登录则获得信息，未登录则跳转到登录界面
    var lgc = getCookie('userName')
    if (lgc) {
        signUser.style.display = 'block'
        signTips.style.display = 'none'
        var userNameVal = signUser.getElementsByClassName('lg-user')[0]
        userNameVal.innerHTML = `欢迎您,${lgc}`
        outUserName.onclick = function () {
            signUser.style.display = 'none'
            signTips.style.display = 'block'
            delCookie('userName')
            location.reload()
        }
    } else { location.href = "./login.html?ReturnUrl=" + encodeURIComponent(location.href) }
    //ajax动态生成用户名的购物车数据
    goodsReload()
    function goodsReload() {
        ajax({
            type: 'post',
            url: 'http://43.138.81.225/demo/php/searchShoppingCarByUser.php',
            data: { user: lgc },
            callback: function (res) {
                var { status, message, list } = res
                if (res.status) {
                    if (list.length > 0) {
                        var html = ``
                        list.forEach(({ id, gid, buyNum, goodsName, goodsImg, goodsPrice }) => {
                            html += `
                <tr data-goodsid=${id}>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="${goodsImg}" alt="" /><span>${goodsName}</span></td>
                    <td class="price">${parseInt(goodsPrice).toFixed(2)}</td>
                    <td class="count">
                        <span class="reduce">${buyNum > 1 ? "-" : ""}</span>
                        <input class="count-input" type="text" value="${buyNum}" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">${(goodsPrice * buyNum).toFixed(2)}</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>          
                `})
                        tbody.innerHTML = html
                    } else {
                        catbox.innerHTML = ` <div class="empty">
                    <div class="title">您的购物车还是空的！</div>
                    <div class="showImg">
                        <img src="https://cdn.cnbj1.fds.api.mi-img.com/staticsfile/cart/cart-empty.png" alt="">
                    </div>
                </div>`
                    }
                }
            }
        })
    }
    //给整个父元素绑定点击事件
    catbox.addEventListener("click", shoppingCarHandler)
    //事件委托，全部委托给父元素
    function shoppingCarHandler(e) {
        // this -> 绑定事件的元素  catbox
        // target -> 触发事件的元素 事件源(可以是catbox子代元素中的每一个)
        var e = e || window.event
        var target = e.target  //事件源(触发事件的元素)
        if (target.classList.contains("check-all")) {
            checkAllHandler(target)
            getTotal()
        } else if (target.classList.contains("check-one")) {
            isAllChecked()
            getTotal()
        } else if (target.className == "add") {
            addHandler(target)
            getTotal()
        } else if (target.className == "reduce") {
            reduceHandler(target)
            getTotal()
        } else if (target.className == "delete") {
            deleteOneHandler(target)
            isAllChecked()
            getTotal()
        } else if (target.id == "deleteAll") {
            deleteAllHandler()

            getTotal()
        }
    }
    //单选跟全选走
    function checkAllHandler(target) {
        var status = target.checked
        for (var i = 0; i < checkOneList.length; i++) {
            var checkOne = checkOneList[i]
            checkOne.checked = status
        }
    }
    //判断是否是全部选中
    function isAllChecked() {
        // debugger
        var flag = Array.from(checkOneList).every(item => item.checked)
        checkAll.checked = checkOneList.length > 0 ? flag : false
        console.log(flag)
    }
    //增加数量
    function addHandler(target) {
        // a. 输入框  数量 加一 
        var countInput = target.previousElementSibling
        var num = countInput.value
        num++
        countInput.value = num
        // b. 小计更新  =  单价*数量
        var countTd = target.parentElement.previousElementSibling
        var subtotalTd = target.parentElement.nextElementSibling
        // 注意:如果有单位  "5999.88元"  "¥5999.88"  => 处理(去单位)
        var price = countTd.textContent
        var subtotal = price * num
        subtotalTd.textContent = subtotal.toFixed(2)
        // 3. 减号按钮的 “-”  出现
        var reduce = countInput.previousElementSibling
        reduce.textContent = "-"
        //在数据库中增加这个商品的数量
        var tr = target.parentElement.parentElement
        var id = tr.dataset.goodsid
        ajax({
            type: 'post',
            url: 'http://43.138.81.225/demo/php/updateShoppingCarById.php',
            data: {
                id: id,
                buyNum: 1,
                type: 1
            }
        })
    }
    //减少数量
    function reduceHandler(target) {
        // a. 输入框  数量 减一 
        var countInput = target.nextElementSibling
        var num = countInput.value
        // c .减之前  判断  如果数量为1  不能减     return false
        if (num <= 1) { return false }
        num--  //自减
        //d. 减之后  判断  如果数量为1(2切为1)  减号按钮的 “-” 消失
        if (num <= 1) {
            target.textContent = ""
        }
        countInput.value = num
        var countTd = target.parentElement.previousElementSibling
        var subtotalTd = target.parentElement.nextElementSibling
        // b. 小计更新
        // 注意:如果有单位  "5999.88元"  "¥5999.88"  => 处理(去单位)
        var price = countTd.textContent
        var subtotal = price * num
        subtotalTd.textContent = subtotal.toFixed(2)
        //数据库删除这个商品的数量
        var tr = target.parentElement.parentElement
        var id = tr.dataset.goodsid
        ajax({
            type: 'post',
            url: 'http://43.138.81.225/demo/php/updateShoppingCarById.php',
            data: {
                id: id,
                buyNum: 1,
                type: 0
            }
        })
    }
    //单独删除
    function deleteOneHandler(target) {
        if (confirm('是否确认删除这个商品腻？')) {
            var tr = target.parentElement.parentElement
            var id = tr.dataset.goodsid
            ajax({
                type: "get",
                url: "http://43.138.81.225/demo/php/deleteShoppingCarById.php",
                data: {
                    id: id
                },
                dataType: "json",
                callback: function (result) {
                    var { status, message } = result
                    if (status) {
                        tr.remove()   // 先删除数据 再删页面
                        isAllChecked()
                        if (checkOneList.length == 0) {
                            goodsReload()
                        }
                    } else {
                        alert(message)
                    }
                }
            })
        }
    }
    //删除全部
    function deleteAllHandler() {
        var delIdList = Array.from(checkOneList).filter(check => check.checked).map(check => {
            var tr = check.parentElement.parentElement
            var id = tr.dataset.goodsid
            return id
        })
        ajax({
            url: 'http://43.138.81.225/demo/php/deleteShoppingCarById.php',
            data: {
                id: delIdList.join(',')
            },
            callback: function (res) {
                var { status, message } = res
                if (status) {
                    for (var j = 0; j < checkOneList.length; j++) {
                        var checkOne = checkOneList[j]
                        if (checkOne.checked) {
                            var tr = checkOne.parentElement.parentElement
                            tr.remove()
                            j--
                        }
                    }
                    isAllChecked()
                    if (checkOneList.length == 0) {
                        goodsReload()
                    }
                } else {
                    alert(message)
                }
            }
        })
    }
    //结算
    function getTotal() {
        var sum = 0  // 被选中的商品的数量
        var allPrice = 0  // 被选中的商品的总价格
        // 找到所有选中状态的单选  => 通过它找到该商品对应的数量和小计  => 累加
        for (let j = 0; j < checkOneList.length; j++) {
            var item = checkOneList[j]
            if (item.checked) {
                var tr = item.parentElement.parentElement   // 选中状态的单选 => tr
                var countInput = tr.getElementsByClassName("count-input")[0]
                var subtotalTd = tr.getElementsByClassName("subtotal")[0]
                // console.log(countInput, subtotalTd) 
                var num = countInput.value * 1
                var subtotal = subtotalTd.textContent * 1
                sum += num
                allPrice += subtotal
            }
        }
        selectedTotal.textContent = sum
        priceTotal.textContent = allPrice.toFixed(2)
    }



</script>

</html>